﻿Imports System.DirectoryServices


Public Class ADTypeConversion

    Public Shared Function DNtoSAM(ByVal DN As String) As String

        If String.IsNullOrEmpty(DN.Trim) Then
            Throw New ArgumentException("Empty DN string passed to Active Directory conversion")
        End If

        Dim de As New DirectoryEntry("LDAP://" & dn)
        de.AuthenticationType = AuthenticationTypes.ReadonlyServer

        DNtoSAM = CType(de.Properties("sAMAccountName")(0), String)

        de.Dispose()

    End Function

    Public Shared Function SAMtoDN(ByVal FQDN As String, ByVal SAM As String) As String

        Dim de As New DirectoryEntry("LDAP://" & FQDN)
        Dim ds As New DirectorySearcher(de, String.Format("(&(objectCategory=group)(samaccountname={0}))", _
                                                               SAM))

        Dim dr As SearchResult = ds.FindOne

        SAMtoDN = dr.Properties("distinguishedname")(0).ToString

        ds.Dispose()
        de.Dispose()

    End Function


End Class
